package com.example.controller.before;

import com.example.entity.User;
import com.example.entity.vo.RegisterVo;
import com.example.service.UcenterMemberService;
import com.example.service.UserService;
import com.example.utils.JwtUtils;
import com.example.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-08-15
 */
@Api(tags = "小程序登录模块")
@RequestMapping("/loginBefore")
@RestController
@CrossOrigin
public class LoginControllerBefore {

    @Autowired
    private UcenterMemberService memberService;

    @Autowired
    private UserService userService;

    @ApiOperation(value = "登录")
    @PostMapping("login")
    public R loginUser(@RequestBody User member) {
        //调用service方法实现登录
        //返回token值，使用jwt生成
        String token = memberService.login(member);
        return R.ok().data("token", token);
    }

    @ApiOperation(value = "注册")
    @PostMapping("register")
    public R registerUser(@RequestBody RegisterVo registerVo) {
        memberService.register(registerVo);
        return R.ok();
    }

    @ApiOperation(value = "根据token获取用户信息")
    @GetMapping("getMemberInfo")
    public R getMemberInfo(HttpServletRequest request) {
        //调用jwt工具类方法，根据request对象获取头信息，返回用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        //查询数据库用户id获取用户信息
        User member = userService.getById(memberId);
        return R.ok().data("userInfo", member);
    }

}

